/*
 * Copyright (c) 2012 Sean Connelly
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var common = require('./common.js');
var typeTracker = require('./type-tracker.js');
var preDefined = require('./pre-defined.js');

// compiler transformations start with "cr", short for (C)ompile (R)ho
var crMarkScopes = require('./cr-mark-scopes.js').run;

var compile_tgts = {
		'base': require('./compile-rho-base.js'),
		'x64': require('./compile-rho-x64.js')
	};

function compileRho_bounce(ast)
{
	// MYTODO: this
}

function compileRho_analyze(ast, fileInfo)
{
	var rho_obj = { ast: ast };

	rho_obj.types = typeTracker.create(fileInfo);

	// load the AST definitions into the type tracker
	rho_obj.types.loadAst(preDefined.getAst());
	rho_obj.types.injectPatternedTypes();
	rho_obj.types.loadAst(rho_obj.ast);

	// mark scopes
	crMarkScopes(rho_obj);

	return rho_obj;
}

function compileRho_compile(ast, target, opts, fileInfo)
{
	if (typeof compile_tgts[target] === 'undefined')
		throw 'invalid target: ' + target;

	// step 1. execute `bounce` statements
	compileRho_bounce(ast);

	// step 2. semantic analysis
	var rho_obj = compileRho_analyze(ast, fileInfo);

	// step 3. ...and beyond
	// MYTODO: all this...

	return compile_tgts[target].compile(rho_obj);
}

function compileRho_targets()
{
	var t = [];
	for (var k in compile_tgts)
		t.push(k);
	return t.sort();
}

exports.compile = compileRho_compile;
exports.targets = compileRho_targets;
